using System;
using System.Net;
using System.Text;
using UnityEngine;

namespace JEngine.Framework
{
    [HttpMessageHandler]
    public abstract class HttpHandler<Message> : IMHandler where Message : class
    {
        private HttpListenerContext context;
        protected abstract void Run(Message message);

        public void Handle(string message, HttpListenerContext context)
        {
            this.context = context;
            Message msg = JsonToObj<Message>(message);
            Run(msg);
        }

        protected void Send(object msg)
        {
            try
            {
                var json = LitJson.JsonMapper.ToJson(msg);
                byte[] buffer = Encoding.UTF8.GetBytes(json);

                // 设置响应头信息
                context.Response.ContentType = "text/html";
                context.Response.ContentLength64 = buffer.Length;

                // 发送响应内容
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                context.Response.OutputStream.Close();

                // 关闭连接
                context.Response.Close();
            }
            catch (Exception e)
            {
                Debug.LogError($"发送消息失败:{e}");
            }
        }

        protected T JsonToObj<T>(string json)
        {
            return LitJson.JsonMapper.ToObject<T>(json);
        }

        public Type GetMessageType()
        {
            return typeof(Message);
        }
    }
}